#!/bin/sh

# This script sets method "efi" for all fat16/fat32 partitions that
# have the bootable flag set.

# It's 2020, always create ESP
> /var/lib/partman/efi

. /lib/partman/lib/base.sh

gpt_efi_type=c12a7328-f81f-11d2-ba4b-00a0c93ec93b
msdos_efi_type=0xef
esp_minimum_size=$((50 * 1024 * 1024))

NUM_ESP=0
NUM_NO=0

for dev in /var/lib/partman/devices/*; do
	[ -d "$dev" ] || continue
	cd $dev

	open_dialog GET_LABEL_TYPE
	read_line label_type
	close_dialog

	partitions=
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		if [ $size -lt $esp_minimum_size ]; then
			:
		elif [ "$fs" = fat16 ]; then
			partitions="$partitions $id"
		elif [ "$fs" = fat32 ] && echo "$name" |
                     grep -i "^EFI System Partition" >/dev/null; then
			partitions="$partitions $id"
		elif [ "$label_type" = msdos ] && \
		     [ "$(blkid -o value -s PART_ENTRY_TYPE -p "$path" 2>/dev/null)" = "$msdos_efi_type" ]; then
			partitions="$partitions $id"
		elif [ "$label_type" = gpt ] && \
		     [ "$(blkid -o value -s PART_ENTRY_TYPE -p "$path" 2>/dev/null)" = "$gpt_efi_type" ]; then
			partitions="$partitions $id"
		else
			if [ "$fs" != "free" ]; then
				NUM_NO=$(($NUM_NO + 1))
			fi
		fi
	done
	close_dialog

	for id in $partitions; do
	efi=no
	open_dialog GET_FLAGS $id
	while { read_line flag; [ "$flag" ]; }; do
		if [ "$flag" = boot ]; then
			efi=yes
			NUM_ESP=$(($NUM_ESP + 1))
			# cannot break here
		else
			NUM_NO=$(($NUM_NO + 1))
		fi
	done
	close_dialog
	if [ "$efi" = yes ]; then
		mkdir -p $id
		echo efi >$id/method
	fi
	done
done

log "Found $NUM_ESP ESPs, $NUM_NO non-ESPs"

echo $NUM_ESP >/var/lib/partman/efi_esp_count
